//
//  UpdateVersion.m
//  DALIRemote
//
//  Created by Lawrence on 15/9/10.
//  Copyright (c) 2015年 zdgzled. All rights reserved.
//

#import "UpdateVersion.h"

@implementation UpdateVersion
+(NSDictionary *)CheckUpdate:(BOOL)ischeck{
    UpdateVersion *update=[[UpdateVersion alloc] init];
    NSDecimalNumber *currentVersion = [NSDecimalNumber decimalNumberWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *updateData = [update checkUpdateVersion];
    NSDecimalNumber *updateVersion = [NSDecimalNumber decimalNumberWithString:[updateData objectForKey:@"version"]];
    NSDecimalNumber *ignoreVersion = [NSDecimalNumber decimalNumberWithString:[defaults objectForKey:@"ignoreVersion"]];
    NSDictionary *returnDit = ([updateVersion doubleValue]- [currentVersion doubleValue] > 0.0000001 )? updateData : nil ;
    NSLog(@"%@",returnDit);
    return ischeck == YES ? ([ignoreVersion doubleValue] != [updateVersion doubleValue] ? returnDit : nil) : returnDit ;
}
#pragma 获取本地版本
-(NSString *)GetlocalVersion{
    NSDictionary *dict=[[NSBundle mainBundle] infoDictionary];
    return [dict objectForKey:@"CFBundleVersion"];
}
#pragma mark 解析josn数据
-(NSDictionary *)handlerJSONData:(NSData *) data{
    if (data!=nil) {
        NSError *error;
        //解析josn 数据
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
        return dict;
    }
    return nil;
}
#pragma mark 请求版本数据
-(NSDictionary *)checkUpdateVersion{
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=980185110"]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:4];
    [request setHTTPMethod:@"POST"];
    NSHTTPURLResponse *urlResponse=nil;
    NSError *error=nil;
    //异步机制获取数据
    NSData *recervedData=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    NSDictionary *dict=[self handlerJSONData:recervedData];
    if (dict) {
        NSArray *results=[dict objectForKey:@"results"];
        if (results&&results.count!=0) {
            NSDictionary *resultsDict=[results objectAtIndex:0];
            NSString *appstoreVersion=[resultsDict objectForKey:@"version"];
            if (appstoreVersion&&![appstoreVersion isEqualToString:[self GetlocalVersion]]) {
                return resultsDict; //返回解析后的josn 数据
            }
        }
    }

    return false;
}
@end
